<template>
  <div class="login-view">
    <px-container>
      <div class="login-container">
        <!-- 登录卡片 -->
        <div class="login-card pixel-border">
          <div class="login-header">
            <div class="logo-section">
              <div class="logo pixel-border">
                🎓
              </div>
              <h1 class="login-title">系统登录</h1>
              <p class="login-subtitle">
                北京交通大学教室查询系统
              </p>
            </div>
          </div>

          <div class="login-body">
            <!-- 系统状态检查 -->
            <div class="status-check pixel-border" v-if="checkingStatus">
              <px-space align="center">
                <div class="loading-spinner">⟳</div>
                <span>正在检查系统状态...</span>
              </px-space>
            </div>

            <!-- 登录表单 -->
            <form @submit.prevent="handleLogin" v-if="!checkingStatus">
              <px-space direction="vertical">
                <div class="form-group">
                  <label for="username">学号</label>
                  <px-input
                    id="username"
                    v-model="loginForm.username"
                    placeholder="请输入学号"
                    size="large"
                    :disabled="isLoading"
                    required
                  />
                </div>

                <div class="form-group">
                  <label for="password">密码</label>
                  <px-input
                    id="password"
                    v-model="loginForm.password"
                    type="password"
                    placeholder="请输入密码"
                    size="large"
                    :disabled="isLoading"
                    required
                  />
                </div>

                <div class="form-actions">
                  <px-button
                    type="submit"
                    theme="primary"
                    size="large"
                    :loading="isLoading"
                    :disabled="!canLogin"
                    style="width: 100%;"
                  >
                    {{ isLoading ? '登录中...' : '登录系统' }}
                  </px-button>
                </div>
              </px-space>
            </form>

            <!-- 错误信息 -->
            <div class="error-section" v-if="errorMessage">
              <div class="error-message pixel-border">
                <span>⚠️</span>
                <span>{{ errorMessage }}</span>
              </div>
            </div>

            <!-- 成功信息 -->
            <div class="success-section" v-if="successMessage">
              <div class="success-message pixel-border">
                <span>✅</span>
                <span>{{ successMessage }}</span>
              </div>
            </div>
          </div>

          <div class="login-footer">
            <px-space>
              <router-link to="/chat">
                <px-link href="/chat" theme="primary">
                  直接对话 →
                </px-link>
              </router-link>
            </px-space>
          </div>
        </div>
      </div>
    </px-container>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useSystemStore } from '@/stores/system'
import type { LoginCredentials } from '@/types'

const router = useRouter()
const systemStore = useSystemStore()

// 响应式数据
const checkingStatus = ref(true)
const isLoading = ref(false)
const errorMessage = ref('')
const successMessage = ref('')

const loginForm = ref<LoginCredentials>({
  username: '',
  password: ''
})

const systemStatus = computed(() => systemStore.systemStatus)

// 计算属性
const canLogin = computed(() => {
  return loginForm.value.username.trim() &&
         loginForm.value.password.trim() &&
         !isLoading.value &&
         systemStatus.value.app_initialized &&
         systemStatus.value.agent_ready
})

// 方法
const checkSystemStatus = async () => {
  try {
    await systemStore.fetchSystemStatus()
  } catch (error) {
    console.error('系统状态检查失败:', error)
    errorMessage.value = '无法连接到后端服务，请检查网络连接'
  } finally {
    checkingStatus.value = false
  }
}

const handleLogin = async () => {
  if (!canLogin.value) return

  errorMessage.value = ''
  successMessage.value = ''
  isLoading.value = true

  try {
    const response = await systemStore.login(loginForm.value)

    if (response.success) {
      successMessage.value = response.message

      // 登录成功，延迟跳转
      setTimeout(() => {
        router.push('/chat')
      }, 2000)
    } else {
      errorMessage.value = response.message
    }
  } catch (error: any) {
    console.error('登录失败:', error)
    if (error.response?.data?.detail) {
      errorMessage.value = error.response.data.detail
    } else {
      errorMessage.value = '登录失败，请检查网络连接或稍后重试'
    }
  } finally {
    isLoading.value = false
  }
}

onMounted(() => {
  checkSystemStatus()

  // 如果已经登录，直接跳转到聊天页面
  if (systemStore.isAuthenticated) {
    router.push('/chat')
  }
})
</script>

<style scoped>
.login-view {
  min-height: calc(100vh - 200px);
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
}

.login-view::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background:
    repeating-linear-gradient(
      0deg,
      transparent,
      transparent 10px,
      rgba(255, 255, 255, 0.03) 10px,
      rgba(255, 255, 255, 0.03) 20px
    );
  pointer-events: none;
}

.login-container {
  max-width: 500px;
  margin: 0 auto;
  position: relative;
  z-index: 1;
}

.login-card {
  background: white;
  padding: 40px;
  box-shadow:
    8px 8px 0 rgba(0, 0, 0, 0.8),
    16px 16px 0 rgba(0, 0, 0, 0.4);
  max-width: 90%;
  margin: 0 auto;
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.logo {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  background-color: var(--pixel-primary);
  color: white;
  margin-bottom: 8px;
}

.login-title {
  font-size: 24px;
  color: var(--pixel-primary);
  text-shadow: 2px 2px 0 rgba(0, 0, 0, 0.3);
}

.login-subtitle {
  font-size: 12px;
  color: var(--pixel-secondary);
}

.status-check {
  padding: 16px;
  margin-bottom: 24px;
  background: rgba(59, 130, 246, 0.05);
  text-align: center;
}

.loading-spinner {
  font-size: 16px;
  animation: spin 1s linear infinite;
  margin-right: 8px;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  font-size: 12px;
  margin-bottom: 8px;
  color: var(--pixel-dark);
  font-weight: bold;
}

.form-actions {
  margin-top: 32px;
}

.error-section {
  margin-top: 20px;
}

.error-message {
  padding: 12px;
  background: rgba(239, 68, 68, 0.05);
  color: var(--pixel-danger);
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 11px;
}

.success-section {
  margin-top: 20px;
}

.success-message {
  padding: 12px;
  background: rgba(16, 185, 129, 0.05);
  color: var(--pixel-success);
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 11px;
}

.login-footer {
  margin-top: 32px;
  padding-top: 20px;
  border-top: 3px solid #f0f0f0;
  text-align: center;
}

@media (max-width: 768px) {
  .login-card {
    padding: 24px;
    max-width: 95%;
  }

  .logo {
    width: 60px;
    height: 60px;
    font-size: 24px;
  }

  .login-title {
    font-size: 20px;
  }

  .login-subtitle {
    font-size: 11px;
  }
}
</style>